package audit

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/audit"
	auditReq "counter-help/admin/server/model/audit/response"
	"counter-help/admin/server/model/customer"
	"errors"
	"gorm.io/gorm"
)

// AuditEducationVerificationService 声明服务
type EducationVerificationService struct{}
type EducationVerificationWithUser struct {
	audit.EducationVerification
	customer.CusUser
}

// CreateOrUpdateEducationVerification  创建学历认证记录
func (s *EducationVerificationService) CreateOrUpdateEducationVerification(education audit.EducationVerification) error {
	var existingEducation audit.EducationVerification
	// 查找是否已存在此用户的学历认证记录
	if err := global.GVA_DB.Where("user_id = ?", education.UserID).First(&existingEducation).Error; err == nil {
		// 存在记录，执行更新操作
		existingEducation.SchoolName = education.SchoolName
		existingEducation.Degree = education.Degree
		existingEducation.GraduationDate = education.GraduationDate
		// 仅当 CertificatePath 不为空时才更新
		if education.CertificatePath != "" {
			existingEducation.CertificatePath = education.CertificatePath
		}
		existingEducation.IsReviewed = false

		return global.GVA_DB.Save(&existingEducation).Error
	} else if errors.Is(err, gorm.ErrRecordNotFound) {
		// 不存在记录，执行创建操作
		return global.GVA_DB.Create(&education).Error
	} else {
		// 其他错误
		return err
	}
}

// GetEducationVerificationByUserID 根据用户ID获取学历认证信息
func (s *EducationVerificationService) GetEducationVerificationByUserID(userID uint) (audit.EducationVerification, error) {
	var education audit.EducationVerification
	err := global.GVA_DB.Where("user_id = ?", userID).First(&education).Error
	return education, err
}

// ApproveEducation 审核通过
func (s *EducationVerificationService) ApproveEducation(userID uint) error {
	return global.GVA_DB.Model(&audit.EducationVerification{}).
		Where("user_id = ?", userID).Debug().
		Updates(map[string]interface{}{
			"is_reviewed":      true,
			"is_approved":      true,
			"rejection_reason": "",
		}).Error
}

// RejectEducation 审核不通过
func (s *EducationVerificationService) RejectEducation(userID uint, rejectionReason string) error {
	return global.GVA_DB.Model(&audit.EducationVerification{}).
		Where("user_id = ?", userID).
		Updates(map[string]interface{}{
			"is_reviewed":      true,
			"is_approved":      false,
			"rejection_reason": rejectionReason,
		}).Error
}

//// GetPendingEducationVerifications 获取所有未审核的学历认证记录，并手动关联用户信息
//func (s *EducationVerificationService) GetPendingEducationVerifications() ([]auditReq.EducationVerificationResponse, error) {
//	var pendingVerifications []audit.EducationVerification
//	err := global.GVA_DB.
//		Where("is_reviewed = ?", false).
//		Find(&pendingVerifications).Error
//	if err != nil {
//		return nil, err
//	}
//
//	var responses []auditReq.EducationVerificationResponse
//	for _, verification := range pendingVerifications {
//		var user customer.CusUser
//		if err := global.GVA_DB.Where("id = ?", verification.UserID).First(&user).Error; err != nil {
//			return nil, err
//		}
//		responses = append(responses, convertEducationVerificationToResponse(verification, user))
//	}
//	return responses, nil
//}
//
//// GetApprovedEducationVerifications 获取所有已审核的学历认证记录，并手动关联用户信息
//func (s *EducationVerificationService) GetApprovedEducationVerifications() ([]auditReq.EducationVerificationResponse, error) {
//	var approvedVerifications []audit.EducationVerification
//	err := global.GVA_DB.
//		Where("is_reviewed = ?", true).
//		Find(&approvedVerifications).Error
//	if err != nil {
//		return nil, err
//	}
//
//	var responses []auditReq.EducationVerificationResponse
//	for _, verification := range approvedVerifications {
//		var user customer.CusUser
//		if err := global.GVA_DB.Where("id = ?", verification.UserID).First(&user).Error; err != nil {
//			return nil, err
//		}
//		responses = append(responses, convertEducationVerificationToResponse(verification, user))
//	}
//	return responses, nil
//}

// 改版后
func (s *EducationVerificationService) GetPendingEducationVerifications() ([]auditReq.EducationVerificationResponse, error) {
	var responsesEducation []EducationVerificationWithUser
	// 使用联合查询
	err := global.GVA_DB.
		Table("education_verifications").                                        // 指定主表为 user_identities
		Joins("JOIN cus_user ON cus_user.id = education_verifications.user_id"). // 使用正确的表名
		Where("education_verifications.is_reviewed = ?", false).
		Select("education_verifications.*, cus_user.*"). // 选择需要的字段
		Scan(&responsesEducation).Error                  // 使用 Scan 方法将结果存入 responses
	if err != nil {
		return nil, err
	}
	// 处理转换
	var responses []auditReq.EducationVerificationResponse
	for _, identityWithUser := range responsesEducation {
		responses = append(responses, convertEducationVerificationToResponse(identityWithUser.EducationVerification, identityWithUser.CusUser))
	}
	return responses, nil
}

// 改版后
func (s *EducationVerificationService) GetApprovedEducationVerifications() ([]auditReq.EducationVerificationResponse, error) {
	var responsesEducation []EducationVerificationWithUser
	// 使用联合查询
	err := global.GVA_DB.
		Table("education_verifications").                                        // 指定主表为 user_identities
		Joins("JOIN cus_user ON cus_user.id = education_verifications.user_id"). // 使用正确的表名
		Where("education_verifications.is_reviewed = ?", true).
		Select("education_verifications.*, cus_user.*"). // 选择需要的字段
		Scan(&responsesEducation).Error                  // 使用 Scan 方法将结果存入 responses
	if err != nil {
		return nil, err
	}
	// 处理转换
	var responses []auditReq.EducationVerificationResponse
	for _, identityWithUser := range responsesEducation {
		responses = append(responses, convertEducationVerificationToResponse(identityWithUser.EducationVerification, identityWithUser.CusUser))
	}
	return responses, nil
}

// convertEducationVerificationToResponse 转换为包含用户信息的响应结构体
func convertEducationVerificationToResponse(education audit.EducationVerification, user customer.CusUser) auditReq.EducationVerificationResponse {
	return auditReq.EducationVerificationResponse{
		EducationVerification: education,
		User:                  user,
	}
}
